const Koa = require("koa")
const KoaStaticCache = require("koa-static-cache")
const KoaRouter = require("@koa/router")
const Nunjucks = require("nunjucks")
const Mysql = require("mysql2")
const KoaBody = require("koa-body")

// 创建数据库连接
const connection = Mysql.createConnection({
  host: "localhost",
  user: "root",
  password: 'bsc123321',
  database: "kkb"
})

const app = new Koa();

Nunjucks.configure('./template', {
  noCache: true,// 关闭缓存
  watch: true,
})

// 1. 使用静态资源中间件
app.use(KoaStaticCache('./public', {
  prefix: "/public",
  dynamic: true,
  gzip: true,
}))

// 2. 使用路由处理动态资源
const router = new KoaRouter();

// 首页
router.get("/",async ctx =>{
  let categories = query("select * from categories")
  ctx.body = Nunjucks.render("index.html",{
    categories
  })
})

// 注册页
router.get("/register", async ctx => {
  let categories = query('select * from categories')
  ctx.body = Nunjucks.render('register.html',{
    categories
  })
})
// 处理注册
router.post("/register", KoaBody(), async ctx => {
  let {name, password, rePassword} = ctx.request.body;
  if (name && password && rePassword) {
    if (password === rePassword) {
      let res = await query("insert into `users` (`name`,`password`) values (?,?)", [name, password]);
      ctx.body = "注册成功"
    } else {
      ctx.body = "两次密码输入不一致"
    }
  } else {
    ctx.body = "缺少字段"
  }
})

// 登录页
router.get("/login",ctx=>{
  let categories = query('select * from categoryies')
  ctx.body = Nunjucks.render('login.html',{
    categories
  })
})
// 处理登录
router.post("/login",ctx=>{
  let {name, password} = ctx.request.body;
  ctx.body = "登录成功"
})

app.use(router.routes())

// 3. 监听端口
app.listen(8888, () => {
  console.log("启动成功:http://localhost:8888")
})

// 创建sql执行函数
function query(sql, data) {
  return new Promise((resolve, reject) => {
    connection.query(sql, data, function (err, ...data) {
      if (err) {
        reject(err)
      } else {
        resolve(...data);
      }
    })
  })
}